<template>
    <view class="page" :style="{ '--color': color }">
        <status-bar :title="store_id == 0 ? '添加店铺' : '编辑店铺'"></status-bar>
        <view class="padding30">
            <block v-for="(item, index) in formData" :key="index">
                <!-- 单行输入框 -->
                <view class="list" :class="{ required: item.required }" v-if="item.type == 'input'">
                    <view class="color_80">{{ item.title }}：</view>
                    <input class="m-top20" v-model="item.value" :placeholder="item.placeholder" />
                </view>

                <!-- 上传图片 -->
                <view class="list" :class="{ required: item.required }" v-if="item.type == 'img'">
                    <view class="color_80">{{ item.title }}：</view>
                    <view class="row">
                        <block v-if="item.value.length">
                            <view class="p-re" v-for="(subItem, subIndex) in item.value" :key="subIndex">
                                <image :src="$imgUrls(subItem)" mode="aspectFill" class="upload"></image>
                                <text class="iconfont icon-jianshao thmeColor p-ab" @click="delImg(index, subIndex)"></text>
                            </view>
                        </block>
                        <image :src="staticUrl + '/images/jh_up/addImg.png'" class="upload" @click="uploadImage(item.num - item.value.length, index)" v-if="item.value.length < item.num"></image>
                    </view>
                </view>

                <!-- 地址 -->
                <view class="list" :class="{ required: item.required }" v-if="item.type == 'address'">
                    <view class="d-flex">
                        <view class="flex-1 color_80">{{ item.title }}：</view>
                        <view class="thmeColor" @click="locate(index)">
                            <text class="iconfont icon-dingwei"></text>
                            <text class="size28 m-left4">定位</text>
                        </view>
                    </view>
                    <view class="p-top20 p-bot20 bot_bor_ee" @click="locate(index)">
                        <view v-if="item.data.address_province">{{ item.data.address_province }}/{{ item.data.address_city }}/{{ item.data.address_area }}/{{ item.data.address_street }}</view>
                        <view class="color_80" v-else>请选择省/市/区/街道</view>
                    </view>
                    <textarea class="textarea p-top20" v-model="item.value" :placeholder="item.placeholder" :maxlength="-1" auto-height disable-default-padding />

                    <!-- <picker mode="selector" :range="street" range-key="RegionName" @change="streetChange($event, index)">
                        <view>请选择街道</view>
                    </picker> -->
                </view>

                <!-- 富文本 -->
                <view class="list" :class="{ required: item.required }" v-if="item.type == 'richtext'">
                    <view class="color_80">{{ item.title }}：</view>
                    <text-editor :content="item.value" :placeholder="item.placeholder" :index="index" @getContents="getContents"></text-editor>
                </view>
            </block>

            <view class="Wrapper required" v-if="fee.length">
                <text class="title">选择门店类型：</text>
                <view class="row m-top30">
                    <view class="lists" :class="{ Activelist: item.select }" v-for="(item, index) in fee" :key="index" @click.stop="selectStore(item, index)">
                        <text class="name">{{ item.name }}</text>
                        <text class="money">￥{{ item.money }}</text>
                    </view>
                </view>
            </view>

            <view class="btn flexac thmeBg bor_radius_10 size30 white t-letter6" @click="submit">提交</view>
        </view>

        <u-popup :show="show" @close="show = false" :round="10" mode="center" :safeAreaInsetBottom="false" :closeOnClickOverlay="false">
            <view class="Wrappershow">
                <text class="Title">支付</text>
                <view class="d-flex a-center m-top30">
                    <text class="black size32 m-right10">{{ FlagItem.name }}：</text>
                    <view class="d-flex a-center color">
                        <text class="size26 m-top10">￥</text>
                        <text class="Money">{{ FlagItem.money }}</text>
                    </view>
                </view>
                <view class="btns">
                    <view class="btn cancel" @click.stop="cancelBtn">稍后支付</view>
                    <view class="btn config" @click.stop="ConfigBtn">确认支付</view>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
    import { mapState } from 'vuex';
    import textEditor from './components/textEditor.vue';
    import Api from '@/common/Api.js';
    export default {
        data() {
            return {
                staticUrl: this.staticUrl,
                formData: [],
                store_id: '0', // 门店id、0为添加
                street: [], // 街道数据

                // 蹦能通
                show: false,
                fee: [],
                is_star: 0,
                FlagItem: '',
                is_me: 0,
                agent_form: 0,

                // 蹦能通
                p_agent_form: 0,
                bussId: ''
            };
        },
        computed: {
            ...mapState(['color', 'position', 'tdkey', 'bid', 'vid'])
        },
        components: {
            textEditor
        },
        onLoad(e) {
            if (e.is_me) this.is_me = e.is_me;
            if (e.store_id) this.store_id = e.store_id;
            if (e.agent_form) this.agent_form = e.agent_form;
            if (e.p_agent_form) this.p_agent_form = e.p_agent_form;
            if (e.bussId) this.bussId = e.bussId;

            if (this.position.longitude == 0) this.$pop.getLocation();
            this.getInfo();
        },
        async onShow() {
            let options = wx.getEnterOptionsSync();
            if (options.scene == '1038' && options.referrerInfo.appId == 'wxef277996acc166c3' && this.payFlag == 1) {
                let extraData = options.referrerInfo.extraData;
                if (!extraData) return;
                this.show = false;
                if (extraData.code == 'success') {
                    this.$Toast('支付成功');
                }
            }
        },
        methods: {
            getInfo() {
                this.$http
                    .post({
                        url: '/userAgentApi/getStoreDataInfo',
                        data: {
                            store_id: this.store_id,
                            is_me: this.is_me,
                            agent_form: this.agent_form
                        }
                    })
                    .then((res) => {
                        if (res.errcode != 100) return this.$Toast(res.msg);
                        this.formData = res.data || [];
                        const feeData = res.fee || [];
                        if (res.my_shop_id) this.store_id = res.my_shop_id;
                        this.is_star = res.is_star || 0;
                        feeData.forEach((item) => {
                            item.select = false;
                        });
                        if (feeData.length == 1) feeData[0].select = true;
                        this.fee = feeData;
                    });
            },
            // 获取编辑器内容
            getContents(html, index) {
                this.formData[index].value = html;
            },
            uploadImage(count, index) {
                uni.chooseImage({
                    count,
                    success: (res) => {
                        res.tempFilePaths.forEach((item) => {
                            this.$common.uploadFiles(item).then((result) => {
                                if (result.errcode != 100) return this.$Toast('上传失败');
                                let Url = result.url.slice(22);
                                this.formData[index].value.push(Url);
                            });
                        });
                    }
                });
            },
            delImg(index, subIndex) {
                this.formData[index].value.splice(subIndex, 1);
            },
            submit() {
                let data = {
                    store_id: this.store_id,
                    is_me: this.is_me,
                    agent_form: this.agent_form,
                    p_agent_form: this.p_agent_form,
                    bussId: this.bussId
                };
                let result = this.formData.find((item) => item.required && (!item.value || !item.value.length));
                if (result) return this.$Toast(result.title + '不能为空');
                let address = this.formData.find((item) => item.type == 'address');
                if (address) {
                    if (!address.data.address_province) return this.$Toast('请定位省市区');
                    data = {
                        ...data,
                        ...address.data
                    };
                }
                this.formData.forEach((item) => {
                    if (item.type == 'img') {
                        // 图片
                        data[item.field_name] = item.value.join();
                    } else {
                        data[item.field_name] = item.value;
                    }
                });

                // 泵能通
                if (this.fee.length) {
                    const Result = this.fee.some((n) => n.select);
                    if (!Result) return this.$Toast('未选择门店');
                    data['is_star'] = 0;
                }

                if (this.is_me == 1) data['is_me'] = this.is_me;
                this.$showLoading('');
                this.$http
                    .post({
                        url: '/userAgentApi/addStoreData',
                        data
                    })
                    .then((res) => {
                        this.$hideLoading();

                        if (this.is_me == 1) {
                            const Flag = this.fee.find((n) => n.select);
                            if (!this.fee.length || this.fee.length == 1 || Flag.money <= 0) return this.$Toast(res.msg);

                            if (Flag.money > 0) {
                                this.FlagItem = Flag;
                                this.show = true;
                            }
                        } else {
                            this.$Toast(res.msg);
                            if (res.errcode != 100) return;
                            if (this.store_id == 0) this.store_id = res.data;
                        }
                    });
            },
            // 打开地图选择位置
            locate(index) {
                uni.chooseLocation({
                    latitude: this.position.latitude,
                    longitude: this.position.longitude,
                    success: (res) => {
                        console.log(res);
                        let i = res.address.indexOf('区');
                        this.formData[index].value = res.address.slice(i + 1) + res.name;
                        this.geocoder(res.longitude, res.latitude, index);
                    },
                    fail(err) {
                        console.log(err);
                    },
                    complete(req) {
                        console.log(req);
                    }
                });
            },
            // 天地图-逆地理解析
            geocoder(lon, lat, index) {
                this.$showLoading('');
                this.$http
                    .get_ds({
                        url: '/geocoder',
                        data: {
                            postStr: {
                                lon,
                                lat,
                                ver: 1
                            },
                            type: 'geocode',
                            tk: this.tdkey
                        }
                    })
                    .then((res) => {
                        this.$hideLoading();
                        if (res.status != 0) return;
                        let result = res.result.addressComponent;
                        console.log(result, 'result');

                        this.formData[index].data = {
                            pointx: lon,
                            pointy: lat,
                            address_province: result.province,
                            address_city: result.city || result.province,
                            address_area: result.county,
                            address_street: result.town,
                            province: this.codeEidt(result.province_code),
                            city: this.codeEidt(result.city_code || result.province_code),
                            district: this.codeEidt(result.county_code),
                            street: result.town_code.slice(3)
                        };
                        // 取后6位
                        // if(result.county_code) this.getDivision(result.county_code.slice(-6))
                    });
            },
            // 查询街道
            getDivision(regioncode) {
                this.$showLoading('');
                this.$http
                    .post({
                        url: '/singleSaleApi/getAdministrativeDivision',
                        data: {
                            regioncode: `${regioncode}00`
                        }
                    })
                    .then((res) => {
                        this.$hideLoading();
                        this.street = res.data || [];
                    });
            },
            streetChange(e, index) {
                let current = this.street[e.detail.value];
                this.formData[index].data.address_street = current.RegionName;
                this.formData[index].data.street = current.RegionCode;
            },
            codeEidt(codeTxt) {
                let result = codeTxt.slice(3) + '00';
                return result;
            },
            selectStore(Item, Index) {
                this.fee.forEach((n, i) => {
                    i == Index ? (n.select = true) : (n.select = false);
                });
            },

            async cancelBtn() {
                this.show = false;
                this.$back();
                // const result = await this.$Modal('提示', '信息已提交,请前往我的余额里面进行充值');
            },
            async ConfigBtn() {
                if (!this.FlagItem.money || this.FlagItem.money <= 0) return (this.show = false);
                const Data = {
                    money: this.FlagItem.money,
                    is_star: this.FlagItem.is_star,
                    VeriCode: this.bid,
                    vId: this.vid
                };
                const RechargeAct = await Api.getRechargeAct(Data);
                console.log(RechargeAct, 'RechargeAct');
                const responseObj = {
                    payType: 1,
                    ...RechargeAct,
                    ...Data
                };
                const Recharge = await Api.Joinrecharge(responseObj);
                if (Recharge.extraData) {
                    this.payFlag = 1;
                    wx.openEmbeddedMiniProgram({
                        appId: Recharge.appId,
                        extraData: Recharge.extraData
                    });
                } else {
                    uni.getProvider({
                        service: 'oauth',
                        success: function (resp) {
                            if (resp.provider) {
                                uni.requestPayment({
                                    provider: resp.provider[0],
                                    orderInfo: data,
                                    timeStamp: data.timeStamp,
                                    nonceStr: data.nonceStr,
                                    package: data.package,
                                    signType: data.signType,
                                    paySign: data.paySign,
                                    success: function () {
                                        this.show = false;
                                    }
                                });
                            }
                        }
                    });
                }
                console.log(Recharge, 'Recharge');
            }
        }
    };
</script>

<style lang="scss" scoped>
    .page {
        background-color: #f5f5f5;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);

        view,
        input {
            font-size: 28rpx;
        }
    }

    .Wrapper {
        padding: 18rpx 50rpx;
        background-color: #fff;
        border-radius: 10rpx;
        position: relative;
        .title {
            color: #808080;
            font-size: 28rpx;
        }
        .lists {
            padding: 18rpx 60rpx;
            border: 1px solid #999;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #fff;
            border-radius: 10rpx;
            margin-right: 70rpx;
            .name {
                color: #808080;
                font-size: 30rpx;
            }
            .money {
                color: #808080;
                font-size: 32rpx;
                margin-top: 10rpx;
            }
        }
        .lists:last-child {
            margin-right: 0;
        }
        .Activelist {
            border: 1px solid var(--color) !important;
            .name,
            .money {
                color: #000;
            }
        }
    }
    // .lists {
    //     padding: 18rpx 50rpx;
    //     border: 1rpx solid #999;
    //     display: flex;
    //     flex-direction: column;
    //     align-items: center;
    //     background-color: #fff;
    //     border-radius: 10rpx;
    //     .name {
    //         color: #808080;
    //         font-size: 28rpx;
    //     }
    //     .money {
    //         color: #808080;
    //         font-size: 28rpx;
    //         margin-top: 10rpx;
    //     }
    // }
    // .Activelist {
    //     border: 1rpx solid #000 !important;
    //     .name,
    //     .money {
    //         color: #000;
    //     }
    // }
    .Wrappershow {
        width: 690rpx;
        padding: 40rpx 30rpx 60rpx 30rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        .Title {
            color: #000;
            font-size: 36rpx;
        }
        .Money {
            font-size: 46rpx;
            font-weight: bold;
            padding-left: 4rpx;
        }
        .btns {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .btn {
                width: 40%;
                height: 80rpx;
                border-radius: 10rpx;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 28rpx;
            }
            .cancel {
                background-color: #f1f1f1;
                color: #999;
            }
            .config {
                background-color: var(--color);
                color: #fff;
            }
        }
    }
    // .Wrapper {
    //     width: 100%;
    //     padding: 50rpx 30rpx;
    //     display: flex;
    //     flex-direction: column;
    //     align-items: center;
    //     .Title {
    //         color: #000;
    //         font-size: 34rpx;
    //     }
    //     .selectStore {
    //         width: 100%;
    //         background: #fff;
    //         border-radius: 10rpx;

    //         margin-bottom: 20rpx;
    //         margin-top: 50rpx;
    //         position: relative;
    //         display: flex;
    //         justify-content: space-evenly;
    //         .lists {
    //             padding: 18rpx 50rpx;
    //             border: 1rpx solid #999;
    //             display: flex;
    //             flex-direction: column;
    //             align-items: center;

    //             border-radius: 10rpx;
    //             .name {
    //                 color: #808080;
    //                 font-size: 28rpx;
    //             }
    //             .money {
    //                 color: #808080;
    //                 font-size: 28rpx;
    //                 margin-top: 10rpx;
    //             }
    //         }
    //         .Activelist {
    //             border: 1rpx solid #000 !important;
    //             .name,
    //             .money {
    //                 color: #000;
    //             }
    //         }
    //     }
    //     .ConfigBtn {
    //         width: 260rpx;
    //         height: 80rpx;
    //         margin: 50rpx auto 0;
    //         display: flex;
    //         justify-content: center;
    //         align-items: center;
    //         color: #fff;
    //         font-size: 28rpx;
    //         border-radius: 10rpx;
    //     }
    // }

    .list {
        background: #fff;
        border-radius: 10rpx;
        padding: 20rpx 20rpx 20rpx 40rpx;
        margin-bottom: 20rpx;
        position: relative;
    }

    .required::before {
        content: '*';
        font-size: 40rpx;
        color: var(--color);
        position: absolute;
        left: 10rpx;
        top: 10rpx;
    }

    .upload {
        width: 130rpx;
        height: 130rpx;
        border-radius: 8rpx;
        margin: 20rpx 20rpx 0 0;
    }

    .icon-jianshao {
        top: 10rpx;
        right: 10rpx;
    }

    .textarea {
        width: 100%;
        min-height: 100rpx;
    }

    .btn {
        width: 260rpx;
        height: 80rpx;
        margin: 80rpx auto 0;
    }
</style>
